package com.ultrasoft.farmasoft.web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import com.ultrasoft.farmasoft.domain.Access;
import com.ultrasoft.farmasoft.domain.Pharmacy;
import com.ultrasoft.farmasoft.domain.Rol;
import com.ultrasoft.farmasoft.domain.User;
import com.ultrasoft.farmasoft.domain.Userpharmacy;
import com.ultrasoft.farmasoft.service.HumanResourcesService;
import com.ultrasoft.farmasoft.util.UtilCommon;
import com.ultrasoft.farmasoft.util.UtilConverter;
import com.ultrasoft.farmasoft.util.UtilUseFulTree;
import com.ultrasoft.farmasoft.validator.AccessValidator;

@Controller
@SessionAttributes({"s_UserPharmacy"}) 
@RequestMapping(value="/RRHH")
public class AdminResourceHumanController {
	
	private final HumanResourcesService humanResourceService;

	private HttpSession session;
	private Userpharmacy s_UserPharmacy;
	private int s_userId;
	private int s_pharmacyId;
	private short temp_menuId=0;
	private short temp_submenuId=0;
	
	@Autowired
    public AdminResourceHumanController(HumanResourcesService humanResourceService) {
        this.humanResourceService = humanResourceService;
    }	
	// 				start esencial
	private boolean sessionControl(HttpServletRequest request){
		boolean res = false;
		session = request.getSession(true);
		if(session.getAttribute("s_UserPharmacy") != null){
			s_UserPharmacy 	= (Userpharmacy)session.getAttribute("s_UserPharmacy");
			s_userId 		= s_UserPharmacy.getUser().getUserId();
			s_pharmacyId 	= s_UserPharmacy.getPharmacy().getPharmacyId();
			res = true;
		}
		return res;
	}
	private String redirectHumanResources(HttpServletRequest request){
		if(!sessionControl(request))
			return "redirect:/index"; 
		else
			return "redirect:/adminHumanResources?"+UtilCommon.menuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.menuId_)+"&"+UtilCommon.subMenuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.subMenuId_); 
	}	
	private String handleRedirectHumanResources(HttpServletRequest request,String headMain) {
    	try {
    		return "redirect:/"+headMain+UtilCommon.menuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.menuId_)+"&"+UtilCommon.subMenuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.subMenuId_); 
		} catch (Exception e) {
			return redirectHumanResources(request);
		}
    }
	// 				end esencial
	private List<Integer> responsePharmacySelected(HttpServletRequest request){
    	List<Integer> r=new ArrayList<Integer>();
    	try {
    		String[] l=request.getParameterValues("userpharmacy.pharmacy.pharmacyId");
    		for (int i = 0; i < l.length; i++) {				
    			r.add(Integer.parseInt(l[i]));
			}
		} catch (Exception e) {	}
    	return r;
    }	
	
	
	
	@RequestMapping(value="/adminHumanResources", method=RequestMethod.GET)
	public String handleRequestAdminHumanResources(SessionStatus status,HttpServletRequest request, Model model)throws ServletException  {
		if(this.sessionControl(request)){
			List<Userpharmacy> userPharmacyActive = humanResourceService.getListUserPharmacy(s_pharmacyId,true);
			if(!userPharmacyActive.isEmpty())
				model.addAttribute("userPharmacyActive",userPharmacyActive);
			List<Userpharmacy> userPharmacyInActive = humanResourceService.getListUserPharmacy(s_pharmacyId,false);
			if(!userPharmacyInActive.isEmpty())
				model.addAttribute("userPharmacyInActive",userPharmacyInActive);
			return UtilCommon.fAdministration_RRHH+"humanResource";
	    }
		else 
			return redirectHumanResources(request);
	}	
	@RequestMapping(value = "/ajaxGiveLowOrHighToUser", method = RequestMethod.GET)
	public @ResponseBody String handleRequestAjaxGiveLowOrHighToUser(@RequestParam Integer pharmacyId,@RequestParam Integer userId,@RequestParam boolean active){
    	Userpharmacy userPharmacy = humanResourceService.searchUserPharmacyByPharmacyIdByUserId(pharmacyId, userId);
		userPharmacy.setActive(active);
		humanResourceService.updateUserPharmacy(userPharmacy);
		int idRol = userPharmacy.getUser().getRolId().getRolId();
    	String tempString="";
         switch (idRol) {
             case 1:  tempString = "El Administrativo General ";
                      break;
             case 2:  tempString = "El Administrador ";
                      break;
             case 3:  tempString = "La Regenta ";
             		  break;
         }
         String lowHigh = "";
         if(active)
        	 lowHigh = " Se dio de Alta a ";
         else
        	 lowHigh = " Se dio de Baja a ";
         return lowHigh+tempString;
    }	
	@RequestMapping(value="/adminUserNew", method=RequestMethod.GET)
	public String handleRequestHumanResourcesAdminUserNew(HttpServletRequest request, Model model) throws ServletException {
		if(this.sessionControl(request)){	// name of mapping with the same name of the database			
			model.addAttribute("menuListOptionForAccess",humanResourceService.getMenuListWithSubmenuAndOptions());
			
			List<Rol> rolList = humanResourceService.getRolList();
			if(!rolList.isEmpty())
				model.addAttribute("rolList",rolList);
			
			List<Pharmacy> pharmacyList = humanResourceService.getListPharmacy();
			if(!pharmacyList.isEmpty())
				model.addAttribute("pharmacyList",pharmacyList);
        	model.addAttribute("access",new Access());	
        	
			return UtilCommon.fAdministration_RRHH+"formHumanResource";
		}else
			return redirectHumanResources(request);
	}	
	@RequestMapping(value="/adminUserNew" , method = RequestMethod.POST)
    public String onSubmitRequestHumanResourcesAdminUserNew(@Valid Access access, BindingResult result,Model model,@RequestParam String action,HttpServletRequest request){
		if( !action.equals("Cancelar")){    
			new AccessValidator(humanResourceService,request,"New").validate(access,result);
			if (result.hasErrors()){
				UtilUseFulTree util=new UtilUseFulTree();
				util.converterToListOfArray(request);

				model.addAttribute("menuListOptionForAccess",humanResourceService.getMenuListWithSubmenuAndOptions());	
				model.addAttribute("listOptionPainted",util.getListOption());
				model.addAttribute("listSubmenuPainted",util.getListSubMenu());
				model.addAttribute("listObjSubmenuPainted",util.getObjListSubMenu());
				model.addAttribute("rolList",humanResourceService.getRolList());
				model.addAttribute("pharmacyList",humanResourceService.getListPharmacy());
				return UtilCommon.fAdministration_RRHH+"formHumanResource";
			}			
			List<Integer> pharmacySelected = responsePharmacySelected(request);
			if(!pharmacySelected.isEmpty()){
				humanResourceService.addUser(access.getUserpharmacy().getUser());
				for (Integer integer : pharmacySelected) {
					humanResourceService.addUserPharmacy(new Userpharmacy(integer,access.getUserpharmacy().getUser().getUserId(),true));	
					humanResourceService.addAccessByRequestByUserPharmacy(request,new Userpharmacy(integer,access.getUserpharmacy().getUser().getUserId(),true));
				}
			}
			return handleRedirectHumanResources(request,"RRHH/adminHumanResources?");
		}else
			return handleRedirectHumanResources(request,"RRHH/adminHumanResources?");	
    }		
	@RequestMapping(value="/adminUserEdit", method=RequestMethod.GET)
	public String handleRequestHumanResourcesAdminUserEdit(HttpServletRequest request, Model model) throws ServletException {
    	List<Access> listAccess = humanResourceService.getAccessList(UtilConverter.converterStringToInteger(request,UtilCommon.userId_),UtilConverter.converterStringToInteger(request,UtilCommon.pharmacyId_));
		if(this.sessionControl(request) && !listAccess.isEmpty()){	// name of mapping with the same name of the database			
			UtilUseFulTree util=new UtilUseFulTree();
			util.converterToListOfArrays(listAccess,humanResourceService.searchUserPharmacyByPharmacyIdByUserId(listAccess.get(0).getAccessPK().getPharmacyId(),listAccess.get(0).getAccessPK().getUserId()));
						
			model.addAttribute("menuListOptionForAccess",humanResourceService.getMenuListWithSubmenuAndOptions());
			model.addAttribute("rolList",humanResourceService.getRolList());
			
			model.addAttribute("listOptionPainted",util.getListOption());
			model.addAttribute("listSubmenuPainted",util.getListSubMenu());
			model.addAttribute("listObjSubmenuPainted",util.getObjListSubMenu());			
			model.addAttribute("pharmacyList",humanResourceService.getListPharmacy());

        	model.addAttribute("access",listAccess.get(0));			
			return UtilCommon.fAdministration_RRHH+"formHumanResource";
		}else
			return redirectHumanResources(request);
	}	
	@RequestMapping(value="/adminUserEdit" , method = RequestMethod.POST)
    public String onSubmitRequestHumanResourcesAdminUserEdit(@Valid Access access, BindingResult result,Model model,@RequestParam String action,HttpServletRequest request){
		if( !action.equals("Cancelar")){
			new AccessValidator(humanResourceService,request,"Edit").validate(access,result);
			if (result.hasErrors()){
				UtilUseFulTree util=new UtilUseFulTree();
				util.converterToListOfArray(request);

				model.addAttribute("pharmacyList",humanResourceService.getListPharmacy());
				model.addAttribute("rolList",humanResourceService.getRolList());
				model.addAttribute("menuListOptionForAccess",humanResourceService.getMenuListWithSubmenuAndOptions());	
				model.addAttribute("listOptionPainted",util.getListOption());
				model.addAttribute("listSubmenuPainted",util.getListSubMenu());
				model.addAttribute("listObjSubmenuPainted",util.getObjListSubMenu());
				return UtilCommon.fAdministration_RRHH+"formHumanResource";
			}				
			User userTemp = humanResourceService.searchUserByUserId(access.getUserpharmacy().getUser().getUserId());
			userTemp.setName(access.getUserpharmacy().getUser().getName());
			userTemp.setLastName(access.getUserpharmacy().getUser().getLastName());
			userTemp.setLastName2(access.getUserpharmacy().getUser().getLastName2());
			userTemp.setCi(access.getUserpharmacy().getUser().getCi());
			userTemp.setGenero(access.getUserpharmacy().getUser().getGenero());
			userTemp.setPhone(access.getUserpharmacy().getUser().getPhone());
			userTemp.setEmail(access.getUserpharmacy().getUser().getEmail());
			userTemp.setRolId(access.getUserpharmacy().getUser().getRolId());

			humanResourceService.updateUser(userTemp);			
			humanResourceService.removeAccessByUserByPharmacyId(access.getUserpharmacy().getUser().getUserId(),UtilConverter.converterStringToInteger(request,UtilCommon.pharmacyId_));
			humanResourceService.addAccessByRequestByUserPharmacy(request,new Userpharmacy(UtilConverter.converterStringToInteger(request,UtilCommon.pharmacyId_),access.getUserpharmacy().getUser().getUserId(),true));
			return handleRedirectHumanResources(request,"RRHH/adminHumanResources?");
		}else
			return handleRedirectHumanResources(request,"RRHH/adminHumanResources?");
    }
	/*
	@RequestMapping(value="/show", method=RequestMethod.GET)
	public String handleRequestShow(HttpServletRequest request, Model model) throws ServletException {
		return UtilCommon.fAdministration_RRHH+"jstreeGraph";
	}*/	
}
